package com.medicine.manage.block;

import com.alibaba.fastjson2.JSON;
import com.medicine.manage.block.domain.UserExtend;
import com.medicine.manage.block.entity.WeBaseSignResult;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.swing.text.html.parser.Entity;
import java.io.IOException;

@Service
public class WeBASESignUtil {
    @Value("${fisco-bcos.webase-sign}")
    private String url;

    //http://localhost:5004/WeBASE-Sign/user/newUser?signUserId={signUserId}&appId={appId}&encryptType=0
    public UserExtend createSignUser(String user){
        UserExtend signUser = null;
        String resultStr = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;

        httpClient = HttpClients.createDefault();
        String urlStr = this.url + "?signUserId=" + user + "&appId=group1&encryptType=0";
        HttpGet httpGet = new HttpGet(urlStr);
        try {
            response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == 200){
                resultStr = EntityUtils.toString(response.getEntity());
                System.out.println(resultStr);
                WeBaseSignResult weBaseSignResult = JSON.parseObject(resultStr, WeBaseSignResult.class);
                System.out.println(weBaseSignResult);
                if(weBaseSignResult.getCode() == 0){
                    signUser = weBaseSignResult.getData();
                }
            }

        } catch (IOException e) {
            try {
                response.close();
                httpClient.close();
            } catch (IOException ex) {

            }
            throw new RuntimeException(e);
        }

        return signUser;
    }
}
